package keeto.com.vn.classified.task;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import keeto.com.vn.classified.core.ClassifiedCore;
import keeto.com.vn.classified.core.ClassifiedListener;
import keeto.com.vn.classified.database.BuiltinService;
import keeto.com.vn.classified.database.BuiltinServiceManager;
import keeto.com.vn.classified.network.IProtocol;
import keeto.com.vn.classified.request.GetProfileInfoRequest;
import keeto.com.vn.classified.request.ValidateUserRequest;
import keeto.com.vn.classified.response.GetProfileInfoResponse;
import keeto.com.vn.classified.response.ValidateUserResponse;
import keeto.com.vn.classified.ui.MainApplication;
import keeto.com.vn.classified.ui.R;
import keeto.com.vn.classified.utils.ImageUtilities;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class TaskLogon extends AbstractTask {
	String username;
	String password;
	String presence;

	private final static String KEY_USER_NAME = "username";
	private final static String KEY_DISPLAY_NAME = "display_name";
	private final static String KEY_GENDER = "Gender";
	private final static String KEY_AREA_ID = "AreaID";
	private final static String KEY_AREA = "AreaName";
	private final static String KEY_EMAIL = "Email";
	private final static String KEY_MOBILE = "Mobile";

	public TaskLogon(ClassifiedListener listener, ClassifiedCore core,
			String username, String password, String present) {
		super(listener, core);
		// TODO Auto-generated constructor stub
		this.username = username;
		this.password = password;
	}

	@Override
	public void run() throws ClientProtocolException, JSONException,
	IOException {

		ValidateUserRequest request = new ValidateUserRequest();
		request.setUsername(username);
		request.setPassword(password);
		ValidateUserResponse response = json.getLogin(request);

		if (IProtocol.STATUS_CODE_OK_200 == response.getReturnCode()) {

			core.setCanLogon(false);
			core.setAuthKey(response.getAuthKey());
			MainApplication.setAuthenKey(response.getAuthKey());
			ClassifiedCore.sessionDuplicate = false;

			ByteArrayOutputStream bytes = new ByteArrayOutputStream();
			InputStream is = null;
			URL url= new URL(response.getAvatar());
			BuiltinService buitinService = new BuiltinService();
			try {

				is = url.openStream ();
				byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time.
				byteChunk=read(is);
				buitinService.setDisplayAvatar(byteChunk);

			}catch (IOException e) {
				Bitmap bitmap = BitmapFactory.decodeResource(core.getContext().getResources(), R.drawable.no_avatar);
				buitinService.setDisplayAvatar(ImageUtilities.bitmap2ByteArray(bitmap,100, Bitmap.CompressFormat.JPEG));
				System.err.printf ("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage());
				e.printStackTrace ();
			}
			
			buitinService.setDisplayName(response.getDisplayName());
			buitinService.setUserName(username);
			buitinService.setPassword(password);
			buitinService.setUserEmail(response.getEmail());
			buitinService.setUserPhone(response.getMobile());
			buitinService.setUserId(response.getId());
			buitinService.setStatusMessage(response.getStatus());
			buitinService.setSupperUser(response.getSuperUser());
			buitinService.setAuthKey(response.getAuthKey());
			buitinService.setAreaID(response.getAreaId());
			if (response.getGender().equals("Nam")){
				buitinService.setSex(1);
			}else{
				buitinService.setSex(0);
			}
			BuiltinServiceManager.getInstance(core.getContext()).saveBuitinService(buitinService);
			if (is != null) { is.close(); }
		}
		for (ClassifiedListener listener : listeners) {
			listener.finishLogon(response.getReturnCode());
		}

	}


	@Override
	public void timeoutCallback() {
		// TODO Auto-generated method stub
		for (ClassifiedListener listener : core.copyAndReconstructListeners(null)) {
			listener.finishLogon(IProtocol.STATUS_CODE_CONNECTION_TIMEOUT_502);
		}
	}
	public static byte[] read(InputStream is) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
		try {
			// Read buffer, to read a big chunk at a time. 
			byte[] buf = new byte[2048];
			int len;
			// Read until -1 is returned, i.e. stream ended.
			while ((len = is.read(buf)) != -1) {
				baos.write(buf, 0, len);
			}
		} catch (IOException e) {
			Log.e("Downloader", "File could not be downloaded", e);
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				// Input stream could not be closed.
			}
		}
		return baos.toByteArray();
	}

}
